package com.xymtop.sqlcater.core.sql.sqlconnecter.entity;


import com.xymtop.sqlcater.core.sql.sqlconnecter.builder.SqlBuilder;
import com.xymtop.sqlcater.core.sql.sqlconnecter.builder.TableSqlBuilder;
import com.xymtop.sqlcater.core.sql.sqlconnecter.entity.enumtype.OrderRule;
import com.xymtop.sqlcater.core.sql.sqlconnecter.entity.enumtype.SqlTableType;
import com.xymtop.sqlcater.core.sql.sqlconnecter.entity.fieldtype.FieldType;
import com.xymtop.sqlcater.core.sql.sqlconnecter.entity.index.SqlIndex;
import lombok.Data;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

//数据表对象
@Data
public class SqlTable implements TableSqlBuilder {

    //需要表所属的数据库，比较好定位
    private String database;

    //表名称
    private String name;

    //表的索引列表
    private List<SqlIndex> indexList;

    //表的所有字段
    private List<SqlField> fields;

    //表的储存类型
    private SqlTableType sqlTableType;

    //表的排序规则
    private OrderRule orderRule;

    //表的大小
    private Float size;

    //表的数据行数
    private int len;


    //建表语句
    private String createSql;

    //表的备注
    private String comment;


    @Override
    public String buildCreateSql() {

        return null;
    }

    @Override
    public String buildInsertSql(Object obj) {
        return null;
    }

    public void init(SqlConnecter sqlConnecter) throws SQLException {

        //下面要获取到数据
        if(name!=null){
           ResultSet resultSet = sqlConnecter.query(QuerySql.QUERYFIEDLS(database,name));

           while (resultSet.next()){

               //新建field
               SqlField sqlField = new SqlField();

               //名称
               sqlField.setName(resultSet.getString("TABLE_NAME"));
               //默认值
               sqlField.setDefaultValue(resultSet.getString("COLUMN_DEFAULT"));
               //是否为空
               sqlField.setIsNull(resultSet.getBoolean("IS_NULLLABEL"));
               //数据类型
               sqlField.setFieldType(getFildType(resultSet.getString("DATA_TYPE")));

               //TODO：数据长度

//               sqlField.setFieldSize(Long.valueOf(resultSet.getString("COLUMN_TYPE").split(")")[1]));

               //字段备注
               sqlField.setComment(resultSet.getString("TABLE_COMMENT"));


               //添加field
               this.fields.add(sqlField);
           }

        }
    }

    private FieldType getFildType(String type) {

        return FieldType.VARCHAR;
    }
}
